package com.cndym.utils.hibernate;

import java.lang.reflect.Field;

public class HqlMaker {
	public static String makeHql(Object object) throws IllegalArgumentException, IllegalAccessException{
		StringBuffer result=new StringBuffer();
		Class objectClass=object.getClass();
		result.append("select o from  "+objectClass.getSimpleName()+" o ");
		Field fields[]=objectClass.getDeclaredFields();
		boolean isWhereExists=false;
		for(Field f:fields){
			String condition=makeFieldSql(f,object,isWhereExists);
			result.append(condition);
			if(condition.length()!=0){
				isWhereExists=true;
			}
		}
		return result.toString();
	}
	public static String makeFieldSql(Field field,Object object,boolean isWhereExists) throws IllegalArgumentException, IllegalAccessException{
		StringBuffer result=new StringBuffer();
		Class fieldType=field.getType();
		field.setAccessible(true);
		Object fieldValue=field.get(object);
		if(fieldType.equals(int.class)&&((Integer)fieldValue)!=0){
			if(isWhereExists==false){
				result.append(" where o."+field.getName()+"="+fieldValue+" ");
			}else{
				result.append(" or o."+field.getName()+"="+fieldValue+" ");
			}
		}
		if(fieldType.equals(String.class)&&fieldValue!=null&&!((String)fieldValue).trim().equals("")){
			if(isWhereExists==false){
				result.append(" where o."+field.getName()+" like '%"+fieldValue+"%' ");
			}else{
				result.append(" or o."+field.getName()+" like '%"+fieldValue+"%' ");
			}
		}
		return result.toString();
	}

}
